package com.zsx.shopping.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsx.shopping.common.api.R;
import com.zsx.shopping.common.api.cart.feign.CartFeignService;
import com.zsx.shopping.common.api.cart.vo.CartItemVO;
import com.zsx.shopping.common.api.cart.vo.CartVO;
import com.zsx.shopping.common.api.order.enums.OrderStatus;
import com.zsx.shopping.common.api.product.feign.ProductFeignService;
import com.zsx.shopping.common.api.seckill.dto.SeckillOrderDto;
import com.zsx.shopping.common.api.seckill.enums.SeckillStatus;
import com.zsx.shopping.common.api.seckill.feign.SeckillFeignService;
import com.zsx.shopping.common.api.user.feign.UserFeignService;
import com.zsx.shopping.common.api.user.vo.ReceiveAddressVO;
import com.zsx.shopping.common.api.ware.dto.LockStockDto;
import com.zsx.shopping.common.api.ware.dto.LockStockItemDto;
import com.zsx.shopping.common.api.ware.feign.WareFeignService;
import com.zsx.shopping.common.enums.CodeMsg;
import com.zsx.shopping.common.exception.ShoppingException;
import com.zsx.shopping.common.session.UserVO;
import com.zsx.shopping.order.constant.OrderConstant;
import com.zsx.shopping.order.entity.Order;
import com.zsx.shopping.order.entity.OrderItem;
import com.zsx.shopping.order.enums.DeliveryType;
import com.zsx.shopping.order.enums.OrderCodeMsg;
import com.zsx.shopping.order.enums.PaymentType;
import com.zsx.shopping.order.form.ConfirmForm;
import com.zsx.shopping.order.interceptor.LoginInterceptor;
import com.zsx.shopping.order.mapper.OrderItemMapper;
import com.zsx.shopping.order.mapper.OrderMapper;
import com.zsx.shopping.order.service.OrderService;
import com.zsx.shopping.order.vo.PayStatusVO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private CartFeignService cartFeignService;

    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private WareFeignService wareFeignService;

    @Resource
    private UserFeignService userFeignService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private SeckillFeignService seckillFeignService;

    @Override
    public String toTrade() {
        UserVO userVO = LoginInterceptor.loginUser.get();
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        operations.set(OrderConstant.ORDER_TOKEN_PREFIX + userVO.getId(), uuid, 30, TimeUnit.MINUTES);
        return uuid;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submitOrder(ConfirmForm confirmForm) {
        repeatedSubmitCheck(confirmForm.getToken());
        CartVO cartVO = cartFeignService.getCart().getData();
        if (cartVO.getItems().size() == 0) {
            throw new ShoppingException();
        }
        cartTotalAmountCheck(cartVO);
        Order order = createOrder(confirmForm, cartVO.getTotalAmount());
        List<OrderItem> orderItems = createOrderItems(cartVO);

        // 保存订单和订单项
        orderMapper.insert(order);
        orderItems.forEach(orderItem -> {
            orderItem.setOrderId(order.getId());
            orderItemMapper.insert(orderItem);
        });

        // 远程锁库存
        LockStockDto lockStockDto = new LockStockDto();
        lockStockDto.setOrderId(order.getId());
        lockStockDto.setOrderSn(order.getOrderSn());
        lockStockDto.setItems(orderItems.stream().map(orderItem -> {
            LockStockItemDto lockStockItemDto = new LockStockItemDto();
            lockStockItemDto.setSkuId(orderItem.getSkuId());
            lockStockItemDto.setSkuName(orderItem.getSkuName());
            lockStockItemDto.setSkuNum(orderItem.getSkuCount());
            return lockStockItemDto;
        }).collect(Collectors.toList()));
        R<Void> r = wareFeignService.lockStock(lockStockDto);
        if (!CodeMsg.SUCCESS.getCode().equals(r.getCode())) {
            throw new ShoppingException(r.getCode(), r.getMsg());
        }

        // 发送订单id至RabbitMQ延迟队列,到期未支付自动关闭订单
        rabbitTemplate.convertAndSend(
                "order-event-exchange",
                "order.create.order",
                order.getId());

        return order.getOrderSn();
    }

    @Override
    public void closeOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (OrderStatus.AWAITING.getCode().equals(order.getStatus())) {
            order.setStatus(OrderStatus.CLOSED.getCode());
            orderMapper.updateById(order);

            // 告诉RabbitMQ释放其他资源(如库存)
            rabbitTemplate.convertAndSend(
                    "order-event-exchange",
                    "order.release.other",
                    orderId);
        }
    }

    @Override
    public Byte getOrderStatus(Long orderId) {
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getId, orderId));
        return order.getStatus();
    }

    @Override
    public PayStatusVO getPayStatus(String orderSn) {
        Order order = baseMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, orderSn));
        PayStatusVO payStatusVO = new PayStatusVO();
        payStatusVO.setOrderId(order.getId());
        payStatusVO.setOrderSn(order.getOrderSn());
        payStatusVO.setPayAmount(order.getPayAmount());
        payStatusVO.setStatus(order.getStatus());
        return payStatusVO;
    }

    @Override
    public void pay(String orderSn) {
        Order order = getBaseMapper().selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, orderSn));
        if (OrderStatus.AWAITING.getCode().equals(order.getStatus())) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            threadPoolExecutor.execute(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                cartFeignService.clearCart();
            });
            threadPoolExecutor.execute(() -> wareFeignService.reduceStock(order.getId()));
            order.setStatus(OrderStatus.COMPLETED.getCode());
            orderMapper.updateById(order);
        }
    }

    @Override
    public void cancelOrder(String orderSn) {
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, orderSn));
        if (OrderStatus.AWAITING.getCode().equals(order.getStatus())) {
            order.setStatus(OrderStatus.CANCEL.getCode());
            orderMapper.updateById(order);

            // 告诉RabbitMQ释放其他资源(如库存)
            rabbitTemplate.convertAndSend(
                    "order-event-exchange",
                    "order.release.other",
                    order.getId());
        }
    }

    @Override
    public void saveSeckillOrder(SeckillOrderDto seckillOrderDto) {
        Long userId = seckillOrderDto.getUserId();
        Long sessionId = seckillOrderDto.getSessionId();
        Long skuId = seckillOrderDto.getSkuId();
        // 获取用户默认收货地址
        ReceiveAddressVO receiveAddressVO = userFeignService.getDefaultReceiveAddress(userId).getData();
        if (receiveAddressVO == null) {
            seckillFeignService.restoreStock(seckillOrderDto.getRandomCode(), seckillOrderDto.getCount());
            seckillFeignService.changeSeckillStatus(userId, sessionId, skuId, SeckillStatus.FAIL1.getCode());
            return;
        }

        Order order = new Order();
        order.setReceiverCity(receiveAddressVO.getCity());
        order.setReceiverDetailAddress(receiveAddressVO.getDetailAddress());
        order.setReceiverName(receiveAddressVO.getName());
        order.setReceiverPhone(receiveAddressVO.getPhone());
        order.setReceiverProvince(receiveAddressVO.getProvince());
        order.setReceiverRegion(receiveAddressVO.getRegion());

        // 默认线上支付,普通快递送货上门
        BigDecimal fare = DeliveryType.ORDINARY.getFare();
        order.setPaymentType(PaymentType.ONLINE.getId());
        order.setDeliveryType(DeliveryType.ORDINARY.getId());
        order.setFare(fare);

        order.setOrderSn(seckillOrderDto.getOrderSn());
        order.setPayAmount(seckillOrderDto.getSeckillPrice().add(fare));
        order.setUserId(userId);
        order.setStatus(OrderStatus.AWAITING.getCode());
        orderMapper.insert(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setSkuCount(seckillOrderDto.getCount());
        orderItem.setSkuId(skuId);
        orderItem.setSkuImage(seckillOrderDto.getDefaultImage());
        orderItem.setSkuName(seckillOrderDto.getSkuName());
        orderItem.setSkuPrice(seckillOrderDto.getSeckillPrice());
        orderItem.setSkuSaleAttrs(seckillOrderDto.getSaleAttrs());
        orderItemMapper.insert(orderItem);

        seckillFeignService.changeSeckillStatus(userId, sessionId, skuId, SeckillStatus.READY.getCode());
    }

    /**
     * 校验防重令牌,防止重复提交
     * @param token 防重令牌
     */
    private void repeatedSubmitCheck(String token) {
        UserVO userVO = LoginInterceptor.loginUser.get();
        // “获取、比较、修改”整个操作必须是原子性的
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstant.ORDER_TOKEN_PREFIX + userVO.getId()), token);
        if (result == null || result == 0L)
            throw new ShoppingException();
    }

    /**
     * 购物车最新总额检查
     * @param cartVO 购物车
     */
    private void cartTotalAmountCheck(CartVO cartVO) {
        Map<Long, Integer> map = cartVO.getItems().stream().collect(Collectors.toMap(CartItemVO::getSkuId, CartItemVO::getCount));
        BigDecimal totalPrice = productFeignService.getTotalPrice(map).getData();
        if(totalPrice.subtract(cartVO.getTotalAmount()).abs().compareTo(new BigDecimal("0.01")) > 0) {
            // 商品价格变动,购物车总额与最新总额不符,更新购物车数据
            cartFeignService.updateCart();
            OrderCodeMsg codeMsg = OrderCodeMsg.PRODUCT_PRICE_CHANGE;
            throw new ShoppingException(codeMsg.getCode(), codeMsg.getMsg());
        }
    }

    /**
     * 创建订单
     * @param confirmForm 订单确认表单
     * @param cartTotalAmount 购物车总额
     * @return 订单
     */
    private Order createOrder(ConfirmForm confirmForm, BigDecimal cartTotalAmount) {
        UserVO userVO = LoginInterceptor.loginUser.get();
        String orderSn = IdWorker.getTimeId();
        DeliveryType deliveryType = Objects.requireNonNull(DeliveryType.valueOf(confirmForm.getDeliveryType()));
        // 订单应付总额 = 购物车总额 + 运费, 本项目没有做优惠系统,因此没有返现等优惠
        BigDecimal payAmount = cartTotalAmount.add(deliveryType.getFare());
        ReceiveAddressVO receiveAddressVO = userFeignService.getReceiveAddress(confirmForm.getReceiveAddressId()).getData();
        if (receiveAddressVO == null) {
            throw new ShoppingException();
        }

        Order order = new Order();
        order.setUserId(userVO.getId());
        order.setPayAmount(payAmount);
        order.setOrderSn(orderSn);
        order.setDeliveryType(confirmForm.getDeliveryType());
        order.setFare(deliveryType.getFare());
        order.setPaymentType(confirmForm.getPaymentType());
        order.setReceiverCity(receiveAddressVO.getCity());
        order.setReceiverDetailAddress(receiveAddressVO.getDetailAddress());
        order.setReceiverName(receiveAddressVO.getName());
        order.setReceiverPhone(receiveAddressVO.getPhone());
        order.setReceiverProvince(receiveAddressVO.getProvince());
        order.setReceiverRegion(receiveAddressVO.getRegion());
        order.setStatus(OrderStatus.AWAITING.getCode());

        return order;
    }

    /**
     * 创建订单项
     * @param cartVO 购物车
     * @return 订单项
     */
    private List<OrderItem> createOrderItems(CartVO cartVO) {
        return cartVO.getItems().stream().map(cartItemVO -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartItemVO.getSkuId());
            orderItem.setSkuCount(cartItemVO.getCount());
            orderItem.setSkuImage(cartItemVO.getImage());
            orderItem.setSkuName(cartItemVO.getTitle());
            orderItem.setSkuPrice(cartItemVO.getPrice());
            orderItem.setSkuSaleAttrs(cartItemVO.getSaleAttrs());
            return orderItem;
        }).collect(Collectors.toList());
    }
}




